<?php


namespace App\Web\Model;

use App\Web\Facades\UserAuth;

use App\Web\Model\CaseFlow;
use App\Web\Model\CaseFlow as CaseModel;
use App\Web\Model\Customer as CustomerModel;
use EchoPHP\Facades\Db;
use EchoPHP\Facades\Log;
use EchoPHP\Facades\Validation;
use EchoPHP\Validator\Validator;
use App\Service\Crmapi as CrmService;

class Customer extends Model {
    private $field = 'CustomerSub.subid,crmsubid,crmcustomerid,subname,subarea,selleremail,sellerid,sellername,sellerphone,industry,CustomerSub.updatedate,leaderphone,leaderemail,max(ischarger) as ischarger';

    /**通过交易公司id获取客户信息
     * @param $subId
     * @return array
     */
    public function detail($subId) {
        if ($subId <= 0) {
            return ['status' => false, 'message' => '查找失败', 'customerInfo' => []];
        }
        $user = UserAuth::getLoginInfo();
        //超管
        if ($user['issuper'] != 1) {
            $result = $this->myCostumer(['subid' => $subId]);
            if (empty($result) || !in_array($subId, array_column($result, 'subid'))) {
                return ['status' => false, 'message' => '您无权查看该信息', 'customerInfo' => []];
            }
        }
        $field = 'subid,crmsubid,subname,subarea,selleremail,sellerid,sellername,sellerphone,industry,leadername,leaderid,introduce,subshowname,creator,leaderphone,leaderemail';
        $sql = 'SELECT ' . $field . ' FROM CustomerSub WHERE subid=?';
        $var = [$subId];
        $result = Db::selectOne($sql, $var);
        $result['ischarger'] = $this->chkEditSubRight($subId);
        return ['status' => true, 'message' => '查找成功', 'customerInfo' => $result];
    }

    public function GetSubOpr($subId) {
        $user = UserAuth::getLoginInfo();
        //超管
        if ($user['issuper'] != 1) {
            $result = (new CustomerModel())->myCostumer(['subid' => $subId]);
            if (empty($result) || !in_array($subId, array_column($result, 'subid'))) {
                return [];
            }
        }
        $sql = 'SELECT DISTINCT subid,userid,cname,ischarger,islock,User.leader,leadername,teamname FROM SubOperator LEFT JOIN User ON oprid=userid LEFT JOIN Team ON User.teamid = Team.teamid
WHERE User.status=? AND SubOperator.status=? AND SubOperator.subid=? ORDER BY SubOperator.id';
        $var = ['01', '01', $subId];
        return Db::select($sql, $var);
    }


    /**通过交易公司ids获取客户信息
     * @param $subId
     * @return array
     */
    public function GetCustomerListByIds($customerIds) {
        if (empty($customerIds)) {
            return null;
        }
        $var = [];
        $inFlag = $this->arrAppand($var, $customerIds);

        $field = 'subid,subname,subarea,selleremail,sellerid,sellername,sellerphone,industry,leadername,leaderid';
        $sql = 'SELECT ' . $field . ' FROM CustomerSub WHERE subid in (' . $inFlag . ')';
        $customerList = Db::select($sql, $var);
        return $customerList;
    }

    /**返回客户的流程
     * @param $subId
     * @return array
     */
    public function Getsubflow($subId) {
        if ($subId <= 0) {
            return [];
        }
        $field = 'tagcode';
        $sql = 'SELECT ' . $field . ' FROM SubFlow WHERE subid=? AND status=?';
        $var = [$subId, '01'];
        $subFlow = Db::select($sql, $var);
        return $subFlow;
    }

    public function myCostumerCount($params) {
        $sql = 'select count(DISTINCT CustomerSub.subid) as count from CustomerSub left join SubOperator on CustomerSub.subid=SubOperator.subid left join User on User.userid=SubOperator.oprid  where User.status = ?  and SubOperator.status= ?';
        if (isset($params['subid']) && $params['subid']) {
            $sql .= ' and CustomerSub.subid = ? ';
            $var[] = $params['subid'];
        }
        if (isset($params['crmsubid']) && $params['crmsubid']) {
            $sql .= ' and CustomerSub.crmsubid = ? ';
            $var[] = $params['crmsubid'];
        }
        if (isset($params['subname']) && $params['subname']) {
            $sql .= ' and CustomerSub.subname like ? ';
            $var[] = '%' . $params['subname'] . '%';
        }
    }

    //客户列表
    public function myCostumer($params, $field = '', $rowFrom = 0, $rowTo = 0) {
        $user = UserAuth::getLoginInfo();
        $field = $field ?: 'CustomerSub.subid,crmsubid,crmcustomerid,subname,subarea,selleremail,sellerid,sellername,sellerphone,industry,CustomerSub.updatedate,leaderphone,leaderemail';

        if ($field == 'count') {
            $sql = 'select count(DISTINCT CustomerSub.subid) as count from CustomerSub left join SubOperator on CustomerSub.subid=SubOperator.subid left join User on User.userid=SubOperator.oprid  where User.status = ? and SubOperator.status=?';
        } else {
            $field .= $user['issuper'] == 1 ? ',1 as ischarger ' : ',max(ischarger) as ischarger ';
            $sql = 'select ' . $field . ' from CustomerSub left join SubOperator on CustomerSub.subid=SubOperator.subid left join User on User.userid=SubOperator.oprid  where User.status = ? and SubOperator.status=? ';
        }
        $var = ['01', '01'];

        if (isset($params['subid']) && $params['subid']) {
            $sql .= ' and CustomerSub.subid = ? ';
            $var[] = $params['subid'];
        }
        if (isset($params['crmsubid']) && $params['crmsubid']) {
            $sql .= ' and CustomerSub.crmsubid = ? ';
            $var[] = $params['crmsubid'];
        }
        if (isset($params['subname']) && $params['subname']) {
            $sql .= ' and CustomerSub.subname like ? ';
            $var[] = '%' . $params['subname'] . '%';
        }
        if (isset($params['subarea']) && $params['subarea']) {
            $sql .= ' and CustomerSub.subarea = ? ';
            $var[] = $params['subarea'];
        }
        //超管 所有项目
        if ($user['issuper'] == 1) {

        } elseif ($user['teamrole'] == '2') {
            // 团队leader 团队下
            $sql .= ' and teamcode like ? ';
            $var [] = $user['teamcode'] . '%';
        } elseif ($user['teamrole'] == '1') {
            // 普通用户 自己
            $sql .= ' and userid = ? ';
            $var [] = [$user['userid']];
        }
        if ($field == 'count') {
            return Db::selectOne($sql, $var);
        }
        $sql .= ' group by CustomerSub.subid order by CustomerSub.subid desc ';
        return Db::select($sql, $var, $rowFrom, $rowTo);
    }

    //客户对接人对接客户列表
    public function oprSubList($userid) {
        $sql = 'select s.subid,s.subname,s.crmsubid from CustomerSub as s  left join SubOperator as so on s.subid = so.subid
                where so.oprid  = ? and so.status = ?';
        return Db::select($sql, [$userid, '01']);
    }

    //项目对接人对接项目的 客户与项目基本信息
    public function oprProjList($userid) {
        $sql = 'select  s.subid,s.subname,p.projectid,p.projectname,s.crmsubid from  Project as p
                left join ProjectOperator as po  on p.projectid = po.projectid
                left join CustomerSub as s  on s.subid = po.subid
                where po.oprid  = ? and po.status = ? group by s.subid';
        return Db::select($sql, [$userid, '01']);
    }

    public function oprProj($subid) {
        $sql = 'select projectid,projectname,crmprojectnum from Project where subid = ? and status = ?';
        return Db::select($sql, [$subid, '01']);
    }

    //检查用户与客户关系决定是否返回所有项目
    public function allProject($subid) {
        //是客户对接人
        $user = UserAuth::getLoginInfo();
        $sql = 'select id from SubOperator where subid = ? and oprid = ? and status = ?';
        $isSubopr = Db::selectOne($sql, [$subid, $user['userid'], '01']);
        if ($isSubopr) {
            return true;
        }
        return false;
    }

    public function subProjopr($userid, $subid) {
        $sql = 'select p.projectid,p.projectname,p.crmprojectnum from ProjectOperator as po
                left join Project as p  on p.projectid = po.projectid
                where po.oprid  = ? and po.status = ? and po.subid = ? and p.status = ?';
        return Db::select($sql, [$userid, '01', $subid, '01']);
    }

    public function search($subID = 0, $subName = '', $rowFrom = 0, $rowTo = 0, $field = '') {
        $field = $field ? $field : 'subid,crmcustomerid,subname,subarea,selleremail,sellerid,sellername,sellerphone,industry,leadername,leaderid,updatedate';
        $sql = 'SELECT ' . $field . ' FROM CustomerSub';

        $where = [];
        $var = [];

        if (!empty($subID)) {
            $where[] = 'subid = ?';
            $var[] = $subID;
        }

        if (!empty($subName)) {
            $where[] = 'subname like ?';
            $var[] = "%" . $subName . "%";
        }

        if (!empty($where)) {
            $sql .= ' WHERE ' . implode(' AND ', $where);
        }
        $sql .= ' ORDER BY updatedate DESC';

        return Db::select($sql, $var, $rowFrom, $rowTo);
    }

    /**
     * Notes:检查客户是否已存在
     * @param $crmSubId
     * @return mixed
     */
    public function chkcrmsubid($crmSubId) {
        $sql = 'SELECT subid,crmsubid FROM CustomerSub WHERE crmsubid=?';
        $subInfo = Db::selectOne($sql, [$crmSubId]);
        if ($subInfo) {//查看该公司是否已存在；
            $sql = 'select oprid,cname,teamname,u.teamid,u.teamcode from SubOperator as so left join User as u on so.oprid = u.userid left join Team as t on u.teamid = t.teamid where so.subid = ? and so.status = ? and ischarger = ?';
            $result = Db::selectOne($sql, [$subInfo['subid'], '01', 1]);
            $message = '客户已存在。<br>';
            if ($result) {
                $fullTeamName = (new Team)->fullName($result['teamcode']);
                $message .= '客户负责人：' . $fullTeamName . ' ' . $result['cname'];
            }
            return ['status' => false, 'message' => $message];
        }
        return ['status' => true, 'message' => '客户不存在'];
    }

    public function Add($params) {
        if (!$params['crmsubid']) {
            return ['status' => false, 'message' => '非法客户ID'];
        }
        if (!$params['tagCode']) {
            return ['status' => false, 'message' => '流程不能为空'];
        }
        if (!$this->chkSubFlow($params['tagCode'])) {
            return ['status' => false, 'message' => '流程排序非法'];
        }
        if (!$params['charger']) {
            return ['status' => false, 'message' => '负责人不能为空'];
        }
        $result = $this->chkcrmsubid($params['crmsubid']);
        if (!$result['status']){
            return $result;
        }

        $rule = [
            'subshowname|显示名称' => [
                'required', 'maxLength' => 100
            ],
            'introduce|公司介绍' => [
                'required', 'maxLength' => 1000
            ]
        ];
        $msg = [];
        $validate = new Validator($rule, $msg);
        $result = $validate->validate([
            'subshowname' => $params['subshowname'],
            'introduce' => $params['introduce']
        ]);
        if (!$result) {
            $errMessages = $validate->getErrors();
            return ['status' => false, 'message' => '字段校验失败', 'validateFailure' => $errMessages];
        }
        $crmService = new CrmService();
        $crmcustomerinfo = $crmService->getCrmCustomerInfo(intval($params['crmsubid']));
        if (empty($crmcustomerinfo)) {
            return ['status' => false, 'message' => '未找到客户信息'];
        }
        //客户账户
        if (!$params['account']) {
            return ['status' => false, 'message' => '无有效客户联系人'];
        }
        if (count($params['account']) != count(array_unique(array_column($params['account'], 'email')))) {
            return ['status' => false, 'message' => '有重复账户邮箱'];
        }
        $errorMsg = $values = $accountVar = [];
        if (count($params['account']) > 50) {
            return ['status' => false, 'message' => '客户联系人一次最多50条'];
        }
        foreach ($params['account'] as $key => $account) {
            if (!Validation::validateEmail('email', $account['email'])) {
                $errorMsg[] = $account['email'] . ' 邮箱格式非法';
                unset($params['account'][$key]);
                continue;
            }
            if (empty($account['cname'])) {
                $errorMsg[] = '联系人名称不能为空';
                unset($params['account'][$key]);
                continue;
            }
        }
        if (empty($params['account'])) {
            return ['status' => false, 'message' => '无有效客户联系人', 'errorList' => $errorMsg];
        }

        $subId = 0;
        Db::connect('jyrpo_pdo')->transaction(function () use ($params, $crmcustomerinfo, &$subId) {
            $crmInfo = [
                $crmcustomerinfo['accsubid'],
                $crmcustomerinfo['subname'],
                $crmcustomerinfo['accid'],
                $crmcustomerinfo['accname'],
                $crmcustomerinfo['branch'],
                $crmcustomerinfo['oprname'],
                $crmcustomerinfo['oprid'],
                $crmcustomerinfo['phone'],
                $crmcustomerinfo['email'],
                $crmcustomerinfo['industry'] ?? '',
                $crmcustomerinfo['reporttoname'] ?? '',
                $crmcustomerinfo['reportto'],
                $params['creator'],
                $params['creator'],
                $params['subshowname'],
                $params['introduce'],
                $crmcustomerinfo['reporttophone'],
                $crmcustomerinfo['reporttoemail'],
            ];
            //写入交易公司表 subid
            $sql = 'INSERT INTO CustomerSub (crmsubid,subname,crmcustomerid,crmcustomername,subarea,createdate,updatedate,sellername,sellerid,
                       sellerphone,selleremail,industry,leadername,leaderid,lastsyncdate,creator,updator,subshowname,introduce,leaderphone,leaderemail)
                VALUES(?,?,?,?,?,Now(),Now(),?,?,?,?,?,?,?,Now(),?,?,?,?,?,?)';
            Db::connect('jyrpo_pdo')->insert($sql, $crmInfo);
            $subId = Db::connect('jyrpo_pdo')->getLastInsertId();

            //客户账户
            $accountSql = 'insert into CustomerAccount(subid,creator,updator,email,cname,crmcustomerid,status,mobilephone,department,memo,createdate,updatedate,isinterviewer)
        value ';
            $values = $accountVar = [];
            foreach ($params['account'] as $account) {
                $values[] = '(?,?,?,?,?,?,?,?,?,?,NOW(),NOW(),?)';
                $var1 = [
                    $subId,
                    $params['creator'],
                    $params['creator'],
                    $account['email'],
                    $account['cname'],
                    $crmcustomerinfo['accid'],
                    '01',
                    $account['mobilephone'],
                    $account['department'],
                    $account['memo'],
                    $account['isinterviewer']
                ];
                $accountVar = array_merge($accountVar, $var1);
            }
            $accountSql .= implode(',', $values);
            Db::connect('jyrpo_pdo')->insert($accountSql, $accountVar);

            // 添加客户负责人
            $sql = 'INSERT INTO SubOperator (subid,oprid,status,ischarger,creator,updator,createdate,updatedate) VALUES (?,?,?,?,?,?,Now(),Now())';
            $var1 = [$subId, $params['charger'], '01', 1, $params['creator'], $params['creator']];
            if (!is_array($params['oprId'])) {
                $params['oprId'] = [$params['oprId']];
            }
            if ($params['oprId']) {
                $params['oprId'] = array_diff($params['oprId'], [$params['creator']]);
                if ($params['oprId']) {
                    //客户执行人
                    $values = [];
                    foreach ($params['oprId'] as $item) {
                        $values[] = '(?,?,?,?,?,?,Now(),Now())';
                        $var2 = [$subId, $item, '01', 0, $params['creator'], $params['creator']];
                        $var1 = array_merge($var1, $var2);
                    }
                    $sql .= ',' . implode(',', $values);
                }
            }
            Db::connect('jyrpo_pdo')->insert($sql, $var1);

            //客户流程
            $sql = 'INSERT INTO SubFlow (subid,tagcodelist,status,createdate,updatedate) VALUES(?,?,?,Now(),Now())';
            $var = [$subId, $params['tagCode'], '01'];
            Db::connect('jyrpo_pdo')->insert($sql, $var);
        });
        return ['status' => true, 'message' => '操作成功', 'errorList' => $errorMsg, 'subid' => $subId];
    }

    //检查流程排序是否正常
    public function chkSubFlow($flow) {
        $subFlow = explode(',', $flow);
        if (count($subFlow) > 16) {
            return false;
        }
        $recommendFlowKey = array_search('03', $subFlow);
        $nextFlowKey = $recommendFlowKey + 1;
        if (isset($subFlow[$nextFlowKey]) && $subFlow[$nextFlowKey] != '05') {
            return false;
        }
        $caseFlowModel = new CaseFlow();
        $flowList = $caseFlowModel->getDefaultFlow();
        foreach ($flowList as $item) {
            if ($item['listindex'] != '99') {
                if (!in_array($item['code'], $subFlow)) {
                    return false;
                }
                $basicFlow[$item['listindex']] = $item['code'];
                $basicSubFlow[array_search($item['code'], $subFlow)] = $item['code'];
            }
        }
        sort($basicFlow);
        sort($basicSubFlow);
        return array_values($basicFlow) == array_values($basicSubFlow);
    }

    /**同步交易公司信息
     * @param $subId
     * @return array
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function customerSync($updator, $subId, $crmSubId) {
        $sql = 'select 1 from CustomerSub where subid = ? and crmsubid = ?';
        $subExist = Db::selectOne($sql, [$subId, $crmSubId]);
        if (!$subExist) {
            return ['status' => false, 'message' => '同步失败'];
        }
        $crmService = new CrmService();
        $crmCustomerInfo = $crmService->getCrmCustomerInfo($crmSubId);
        if (empty($crmCustomerInfo)) {// CRM客户信息已经不存在的情况
            Log::error('CRM接口未返回数据', ['crmsubid' => $crmSubId]);
            return ['status' => false, 'message' => '同步失败'];
        }
        $var = [
            $crmCustomerInfo['subname'],
            $crmCustomerInfo['accid'],
            $crmCustomerInfo['accname'],
            $crmCustomerInfo['branch'],
            $crmCustomerInfo['oprname'],
            $crmCustomerInfo['oprid'],
            $crmCustomerInfo['phone'],
            $crmCustomerInfo['email'],
            $crmCustomerInfo['industry'] ?? '',
            $crmCustomerInfo['reportto'],
            $crmCustomerInfo['reporttoname'] ?? '',
            $crmCustomerInfo['reporttophone'],
            $crmCustomerInfo['reporttoemail'],
            $updator,
            $crmCustomerInfo['accsubid'],
        ];
        //更新交易公司表
        $sql = 'UPDATE CustomerSub SET subname=?,crmcustomerid=?,crmcustomername=?,subarea=?,updatedate=Now(),sellername=?,
        sellerid=?,sellerphone=?,selleremail=?,industry=?,leaderid=?,leadername=?,lastsyncdate=Now(),leaderphone=?,leaderemail=?,updator=? WHERE crmsubid=?';
        $updateResult = Db::update($sql, $var);
        $result = [
            'crmsubid' => $crmSubId,
            'subname' => $crmCustomerInfo['subname'],
            'subarea' => $crmCustomerInfo['branch'],
            'selleremail' => $crmCustomerInfo['email'],
            'sellerid' => $crmCustomerInfo['oprid'],
            'sellername' => $crmCustomerInfo['oprname'],
            'sellerphone' => $crmCustomerInfo['phone'],
            'industry' => $crmCustomerInfo['industry'] ?? '',
            'leadername' => $crmCustomerInfo['reporttoname'] ?? '',
            'leaderid' => $crmCustomerInfo['reportto'],
            'leaderphone' => $crmCustomerInfo['reporttophone'],
            'leaderemail' => $crmCustomerInfo['reporttoemail'],
        ];
        return $updateResult ? ['status' => true, 'message' => '同步成功', 'customerinfo' => $result] : ['status' => true, 'message' => '无信息更新'];
    }

    //添加客户执行人
    public function addSubOpr($oprIds, $subId) {
        $userId = UserAuth::getLoginId();
        $inFlag = substr(str_repeat('? ,', (count($oprIds))), 0, -1);
        $sql = 'select oprid from SubOperator where subid = ? and status = ? and oprid in  ( ' . $inFlag . ' )';;
        $subOprExist = array_column(Db::select($sql, array_merge([$subId, '01'], $oprIds)), 'oprid');
        $oprIds = array_diff($oprIds, $subOprExist);

        $sql = 'INSERT INTO SubOperator (subid,oprid,status,ischarger,creator,updator,createdate,updatedate) VALUES ';
        $var = $values = [];
        foreach ($oprIds as $item) {
            $values[] = '(?,?,?,?,?,?,Now(),Now())';
            $var1 = [
                $subId,
                $item,
                '01',
                '0',
                $userId,
                $userId
            ];
            $var = array_merge($var, $var1);
        }
        $sql .= implode(',', $values);
        return Db::insert($sql, $var);
    }

    //转让客户负责人
    public function transferSubCharger($oprId, $subId) {
        $userId = UserAuth::getLoginId();
        $oprIdExist = $this->checkUserExist($oprId);
        if (!$oprIdExist) {
            return false;
        }
        $updateSubOprRight = $this->chkEditSubRight($subId);
        if (!$updateSubOprRight) {
            return false;
        }
        return Db::connect('jyrpo_pdo')->transaction(function () use ($oprId, $userId, $subId) {

            //原有负责人
            $sql = 'update SubOperator set ischarger = ? ,updator = ?, updatedate = NOW() where subid = ? and ischarger = ? and status = ?';
            $var = ['0', $userId, $subId, '1', '01'];
            Db::connect('jyrpo_pdo')->update($sql, $var);
            //新负责人
            $sql = 'update SubOperator set ischarger = ? ,updator = ?, updatedate = NOW() where subid = ? and oprid = ? and status = ?';
            $var = ['1', $userId, $subId, $oprId, '01'];
            $result = Db::connect('jyrpo_pdo')->update($sql, $var);
            return $result == 1;
        });
    }

    //删除客户执行人
    public function delSubOpr($oprId, $subId) {
        $userId = UserAuth::getLoginId();
        $oprIdExist = $this->checkUserExist($oprId);
        if (!$oprIdExist) {
            return false;
        }
        $sql = 'update SubOperator set status = ? ,updator = ?, updatedate = NOW() where subid = ? and oprid = ? and status = ? and ischarger != ?';
        return Db::update($sql, ['06', $userId, $subId, $oprId, '01', '1']) == 1;
    }

    //检查用户id有效
    private function checkUserExist($oprId) {
        $sql = 'SELECT 1 FROM User WHERE status= ? AND userid = ?';
        return Db::selectOne($sql, ['01', $oprId]);
    }

    //检查有修改客户执行人操作权限
    public function chkEditSubRight($subId) {
        $user = UserAuth::getLoginInfo();
        //超管
        if ($user['issuper'] == 1) {
            return true;
        }
        $sql = 'select oprid from SubOperator where subid = ? and ischarger = ? and status = ?';
        $charger = Db::selectOne($sql, [$subId, '1', '01'])['oprid'];
        // 用户是负责人
        if ($charger == $user['userid']) {
            return true;
        }
        //当前用户作为团队leader 团队下有 负责人
        if ($user['teamrole'] != '2') {
            return false;
        }
        $sql = 'select 1 from User where userid = ? and islock = ? and teamcode like ?';
        $var = [$charger, '0', $user['teamcode'] . '%'];
        return !empty(Db::selectOne($sql, $var));
    }

    public function updateSubFlow($updator, $subId, $tagCode) {
        if (!$this->chkEditSubRight($subId)) {
            return ['status' => false, 'message' => '您无权编辑该客户'];
        }
        if (empty($tagCode)) {
            return ['status' => false, 'message' => '流程不能为空'];
        }
        if (!$this->chkSubFlow($tagCode)) {
            return ['status' => false, 'message' => '流程非法'];
        }
        //检验完成，更新流程表
        $sql = 'UPDATE SubFlow SET tagcodelist=?,updatedate=Now() WHERE subid=? AND status=?';
        $var = [$tagCode, $subId, '01'];
        $statement[] = Db::connect()->prepareStatement($sql, $var);
        $sql = 'UPDATE CustomerSub SET updatedate=Now(),updator=? WHERE subid=?';
        $var = [$updator, $subId];
        $statement[] = Db::connect()->prepareStatement($sql, $var);

        $result = Db::connect()->prepareTransactionStatement(false, ...$statement)->execute();
        if ($result) {
            return ['status' => true, 'message' => '操作成功'];
        } else {
            Log::error('数据库事务执行失败', $statement);
            return ['status' => false, 'message' => '操作失败'];
        }
    }

    public function editShowInfo($subId, $subShowName, $introduce, $updator) {
        if (!$this->chkEditSubRight($subId)) {
            return ['status' => false, 'message' => '您无权编辑该客户'];
        }
        $rule = [
            'subshowname|显示名称' => [
                'required', 'maxLength' => 100
            ],
            'introduce|公司介绍' => [
                'required', 'maxLength' => 1000
            ]
        ];
        $msg = [];
        $validate = new Validator($rule, $msg);

        $result = $validate->validate([
            'subshowname' => $subShowName,
            'introduce' => $introduce
        ]);
        if (!$result) {
            $errMessages = $validate->getErrors();
            return ['status' => false, 'message' => '字段校验失败', 'validateFailure' => $errMessages];
        }
        $sql = 'UPDATE CustomerSub SET subshowname=?,introduce=?,updator=?,updatedate=Now() WHERE subid=?';
        $var = [$subShowName, $introduce, $updator, $subId];
        $result = Db::update($sql, $var);
        if ($result) {
            return ['status' => true, 'message' => '更新成功'];
        } else {
            Log::error('更新客户显示名称或介绍失败', ['sql' => $sql, 'var' => $var, 'result' => $result]);
            return ['status' => false, 'message' => '更新失败'];
        }
    }

    //添加面试官
    public function addSubInterviewer($userId, $subId, $params) {
        $sql = 'select count(*) as num from CustomerAccount where subid = ? and status = ? and isinterviewer = ?';
//        $sql = 'select count(*) as num from SubInterviewer where subid = ?  and status = ?';
//        $countNum = Db::selectOne($sql, [$subId, '01'])['num'];
        $countNum = Db::selectOne($sql,[$subId,'01',1])['num'];
        if ($countNum >= 50) {
            return [
                'status' => false,
                'message' => '面试官总数不可以超过50名'
            ];
        }

        $sql = 'select 1 from CustomerAccount where subid = ? and mobilephone = ? and status = ?';
//        $sql = 'select 1 from SubInterviewer where subid = ? and mobilephone = ? and status = ?';
        $phoneExist = Db::select($sql, [$subId, $params['mobilephone'], '01']);
        if ($phoneExist) {
            return [
                'status' => false,
                'message' => '字段校验失败',
                'validateFailure' => ['mobilephone' => '号码已存在']
            ];
        }
        $sql = 'select crmcustomerid from CustomerSub where subid = ?';
        $customerId = Db::selectOne($sql, [$subId])['crmcustomerid'];

        $sql = 'insert into CustomerAccount (subid,crmcustomerid,creator,updator,cname,mobilephone,
        email,department,memo,status,createdate,updatedate,isinterviewer,isscharger,bindehire)
        value (?,?,?,?,?,?,?,?,?,?,NOW(),NOW(),?,?,?)';
//        $sql = 'insert into SubInterviewer (subid,crmcustomerid,creator,updator,cname,mobilephone,
//email,department,memo,status,createdate,updatedate)
//        value (?,?,?,?,?,?,?,?,?,?,NOW(),NOW())';
        $var = [
            $subId,
            $customerId,
            $userId,
            $userId,
            $params['cname'],
            $params['mobilephone'],
            $params['email'],
            $params['department'],
            $params['memo'],
            '01',
            1,
            0,
            0
        ];
        $result = Db::insert($sql, $var);
        $subinterviewerid = '';
        if ($result) {
            $subinterviewerid = Db::getLastInsertId();
        }
        return [
            'status' => $result,
            'message' => $result ? '保存成功' : '保存失败',
            'subinterviewerid' => $subinterviewerid
        ];
    }

    //编辑面试官
    public function editSubInterviewer($userId, $subId, $accountId, $params) {
        $sql = 'select 1 from CustomerAccount where subid = ? and id<>? and mobilephone = ? and status = ? and isinterviewer = ?';
        $phoneExist = Db::select($sql, [$subId, $accountId, $params['mobilephone'], '01', 1]);
        if ($phoneExist) {
            return [
                'status' => false,
                'message' => '字段校验失败',
                'validateFailure' => ['mobilephone' => '号码已存在']
            ];
        }

        $sql = 'update CustomerAccount set cname=?,mobilephone=?,email=?,department=?,memo=?,updator=?,updatedate=NOW() where id=? and subid=? and isinterviewer = ?';
        $var = [
            $params['cname'],
            $params['mobilephone'],
            $params['email'],
            $params['department'],
            $params['memo'],
            $userId,
            $accountId,
            $subId,
            1
        ];

        $result = Db::update($sql, $var);
        return [
            'status' => $result,
            'message' => $result ? '保存成功' : '保存失败'
        ];
    }

    //删除面试官
    public function delSubInterviewer($userId, $subId, $accountId) {
        $sql = 'update CustomerAccount set status=?,updator=?,updatedate=NOW() where id=? and subid=? and status<>? and isinterviewer = ?';
        $var = [
            '06',
            $userId,
            $accountId,
            $subId,
            '06',
            1
        ];

        $result = Db::update($sql, $var);
        return [
            'status' => $result,
            'message' => $result ? '删除成功' : '删除失败'
        ];
    }

    //获取有效的面试官
    public function showSubInterviewer($subId) {
        $sql = 'select id,subid,cname,mobilephone,email,department,memo,status
 from CustomerAccount where subid = ? and status = ? and isinterviewer = ? order by id asc';
        $result = Db::select($sql, [$subId, '01', 1]);
        return $result;
    }


    /**判断是否有编辑客户面试官权限
     * @param $subId
     * @return array
     */
    public function chkEditSubInterviewerRight($subId) {
        $result = $this->chkEditSubRight($subId);
        if ($result) {
            return true;
        }
        $user = UserAuth::getLoginInfo();
        $sql = 'SELECT subid FROM CaseOperator WHERE oprid=? AND subid=? AND status=?';
        $var = [$user['userid'], $subId, '01'];
        $result = Db::selectOne($sql, $var);
        if (isset($result['subid'])) {
            return true;
        }

        $sql = 'SELECT subid FROM ProjectOperator WHERE oprid=? AND subid=? AND status=?';
        $var = [$user['userid'], $subId, '01'];
        $result = Db::selectOne($sql, $var);
        if (isset($result['subid'])) {
            return true;
        }
        return false;
    }

    /**
     * Notes:客户下的项目
     * @param $subId
     * @return array
     */
    public function projectList($subId) {
        $sql = 'select p.projectid,projectname,u.cname,p.createdate,po.oprid,p.status from Project as p left join ProjectOperator as po on p.projectid = po.projectid left join User as u on po.oprid = u.userid where p.subid = ? and po.ischarger = ? order by p.createdate desc';
        $result =  Db::select($sql, [$subId, 1]);
        $projectModel = new Project();
        foreach ($result as &$item){
            $item['status_trans'] = $projectModel->statusMap[$item['status']];
        }
        return $result;
    }

    /**
     * Notes:我的团队下对接的客户id+项目对应客户id 是否有权限
     * @param $subId
     * @return bool
     */
    public function hasSubIdRight($subId) {
        $user = UserAuth::getLoginInfo();
        if ($user['issuper'] == 1) {
            return true;
        }
        $sql = 'select subid from SubOperator as so left join User as u on so.oprid = u.userid where so.status = ? and u.status = ? and u.teamcode like ?  and so.subid = ?';
        $result1 = Db::selectOne($sql, ['01', '01', $user['teamcode'] . '%', $subId]);
        if (isset($result1['subid'])) {
            return true;
        }

        $sql = 'select subid from ProjectOperator where oprid = ? and subid = ? and status = ?';
        $result2 = Db::selectOne($sql, [$user['userid'], $subId, '01']);
        if (isset($result2['subid'])) {
            return true;
        }
        return false;
    }
}